from rest_framework import serializers
from django_redis import get_redis_connection

from .utils import check_save_user_token
from users.models import User
from .models import OAuthQQUser


class QQAuthUserSerializer(serializers.Serializer):
    password = serializers.CharField(label="密码",max_length=20, min_length=8, write_only=True)
    mobile = serializers.RegexField(label="手机号", regex=r"^1[3-9]\d{9}$")
    sms_code = serializers.CharField(label="短信验证码")
    access_token = serializers.CharField(label='操作凭证')

    def validate(self, attrs):

        # 解密ｏｐｅｎ＿ｉｄ(ｑｑ发送的)
        openid = attrs.get("access_token")
        if not openid:
            raise serializers.ValidationError("无效的access_token")
        attrs["openid"] = check_save_user_token(openid)
        # 获取手机号和短信验证码,然后验证短信验证码是否正确
        mobile = attrs.get("mobile")
        sms_code = attrs.get("sms_code")
        conn = get_redis_connection("verify_codes")
        real_sms_code = conn.get("sms_code_%s" % mobile)
        if real_sms_code.decode() !=sms_code:
            raise serializers.ValidationError("短信验证码错误")

        # 按照用户查找用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            password = attrs.get("password")
            if not user.check_userpassword(password):
                raise serializers.ValidationError("密码错误")
            # 将认证后的user放进校验字典中，后续会使用
            attrs["user"] = user
            return attrs
        return attrs


    def create(self,validate_data):
        # 获取校验的用户
        user = validate_data.get("user")
        # 如果用户不存在就创建用户
        if not user:
            user = User.objects.create(
                username=validate_data.get("mobile"),
                password=validate_data.get("password"),
                mobile = validate_data.get("mobile")
            )

        # 绑定openid
        OAuthQQUser.objects.create(
            openid=validate_data.get("openid"),
            user=user
        )
        return user





